package mydemo.springcloudalibaba.cousumer.order.controller;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import mydemo.springcloudalibaba.api.common.entity.CommonResult;
import mydemo.springcloudalibaba.api.common.entity.Payment;
import mydemo.springcloudalibaba.cousumer.order.service.PaymentOpenFiegnService_ForHystrix;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/order")
@Slf4j
//@DefaultProperties(
//        defaultFallback = "paymentInfo_Global_FallbackMethod",
//        // 执行的条件参数，此处为超时5S
//        commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
//})
public class PaymentController {
    // 下面是全局fallback方法
    public CommonResult paymentInfo_Global_FallbackMethod() {
        return new CommonResult(444,"Global异常处理信息，请稍后再试， /(ToT)/");
    }

    @Autowired
    private PaymentOpenFiegnService_ForHystrix paymentOpenFiegnService_forHystrix;

    @RequestMapping("/getHystrix")
    public CommonResult getHystrix(Payment payment){
        return new CommonResult(200,"成功", paymentOpenFiegnService_forHystrix.getPaymentById_success(payment.getId()));
    }
    @RequestMapping("/errorHystrix")
//    @HystrixCommand
    public CommonResult errorHystrix(Payment payment){
        return new CommonResult(200,"成功", paymentOpenFiegnService_forHystrix.getPaymentById_error(payment.getId()));
    }

    // 服务熔断
    @GetMapping("/payment/circuit/{id}")
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),              //是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "3"),    //请求数达到后才计算
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), //休眠时间窗
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),  //错误率达到多少跳闸
    })
    public String paymentCircuitBreaker(@PathVariable("id") Integer id) {
        if(id < 0){
            throw  new RuntimeException("****id 不能为负数");
        }
        String serialNumber = IdUtil.simpleUUID();

        return  Thread.currentThread().getName() + "\t" + "调用成功，流水号：" + serialNumber;
    }

    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id){
        return "id 不能为负数,请稍后再试， o(╥﹏╥)o id: " + id;
    }
}
